//
//  MXLoginController.m
//  HNBaseProject
//
//  Created by xujie on 2024/5/31.
//

#import "MXLoginController.h"
#import <QuartzCore/QuartzCore.h>
#import "MXMobileLoginVC.h"
#import <WXApi.h>
#import "ExpandButton.h"
#import "DCNavigationController.h"
#import "DCTabbarController.h"
#import "AppDelegate.h"
#import "DCWebViewController.h"
@interface MXLoginController ()

@property(nonatomic,strong)UIView           *bgView;//渐变背景
@property(nonatomic,strong)UIImageView      *logoImageV;//logo
@property(nonatomic,strong)UIButton         *loginBtn;//手机号登录
@property(nonatomic,strong)UIButton         *wxBtn;//微信登录
@property(nonatomic,strong)ExpandButton         *choseBtn;//选择
@property(nonatomic,strong)YYLabel          *choseLab;//阅读

@end

@implementation MXLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxLoginSuccess:) name:@"WXLoginNotificaton" object:nil];
    self.bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH*3/4)];
    // 创建渐变层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.bgView.bounds; // 渐变层的大小和位置应该和myView相同
    // 设置渐变色
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString:@"#D4E4FA"].CGColor, (__bridge id)[UIColor colorWithHexString:@"#F0F8FA"].CGColor,(__bridge id)[UIColor colorWithHexString:@"#FFFFFF"].CGColor];
    // 设置渐变点
    gradientLayer.locations = @[@(0.0f),@(0.7f), @(1.0f)];
     
    // 将渐变层添加到myView的图层
    [self.bgView.layer addSublayer:gradientLayer];
    [self.view addSubview:self.bgView];
    
    self.logoImageV = [[UIImageView alloc]init];
    self.logoImageV.image = [UIImage imageNamed:@"login_logo"];
    [self.view addSubview:self.logoImageV];
    
    self.loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginBtn.backgroundColor = [UIColor colorWithHexString:@"#3378F7"];
    [self.loginBtn setTitle:@"手机号登录" forState:UIControlStateNormal];
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.layer.cornerRadius = 21;
    [self.loginBtn addTarget:self action:@selector(mobileLoginClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginBtn];
    
    self.wxBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.wxBtn.backgroundColor = [UIColor clearColor];
    [self.wxBtn setTitle:@"微信账号登录" forState:UIControlStateNormal];
    [self.wxBtn setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
    self.wxBtn.layer.masksToBounds = YES;
    self.wxBtn.layer.cornerRadius = 21;
    self.wxBtn.layer.borderColor=[UIColor colorWithHexString:@"#78787A"].CGColor;
    self.wxBtn.layer.borderWidth=1;
    [self.wxBtn addTarget:self action:@selector(wxLoginClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.wxBtn];
    
    self.choseBtn = [ExpandButton buttonWithType:UIButtonTypeCustom];
    [self.choseBtn setImage:[UIImage imageNamed:@"login_chose"] forState:UIControlStateNormal];
    [self.choseBtn setImage:[UIImage imageNamed:@"login_chose_s"] forState:UIControlStateSelected];
    [self.choseBtn addTarget:self action:@selector(choseclick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.choseBtn];
    
    self.choseLab = [[YYLabel alloc]init];
    self.choseLab.font=[UIFont systemFontOfSize:13];
    self.choseLab.textColor = [UIColor colorWithHexString:@"#999999"];
    self.choseLab.numberOfLines = 0;
    self.choseLab.text = @"我已阅读并同意《隐私协议》，《用户协议》，《喵享家社区规则》";
    [self.view addSubview:self.choseLab];
    
    [self.logoImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(kNavBarHeight+48);
        make.centerX.equalTo(self.view.mas_centerX).offset(0);
        make.width.offset(196);
        make.height.offset(173);
    }];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.logoImageV.mas_bottom).offset(119);
        make.left.offset(15);
        make.right.offset(-15);
        make.height.offset(43);
    }];
    [self.wxBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.loginBtn.mas_bottom).offset(19);
        make.left.offset(15);
        make.right.offset(-15);
        make.height.offset(43);
    }];
    [self.choseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-55);
        make.left.offset(20);
        make.width.height.offset(15);
    }];
    [self.choseLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.choseBtn.mas_right).offset(3);
        make.right.offset(-15);
        make.centerY.equalTo(self.choseBtn.mas_centerY).offset(0);
        make.height.offset(35);
    }];
    NSString *str = @"我已阅读并同意《隐私协议》，《用户协议》，《喵享家社区规则》";
    NSMutableAttributedString *titleText = [[NSMutableAttributedString alloc] initWithString:str];
    NSRange range1 = [str rangeOfString:@"《隐私协议》"];
    NSRange range2 = [str rangeOfString:@"《用户协议》"];
    NSRange range3 = [str rangeOfString:@"《喵享家社区规则》"];
    WEAKSELF
    [titleText setTextHighlightRange:range1 color:[UIColor colorWithHexString:@"#46A0FF"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf gotoWebWithUrl:@"https://www.maoxga.cn/yinsi.html" title:@"隐私协议"];
    }];
    [titleText setTextHighlightRange:range2 color:[UIColor colorWithHexString:@"#46A0FF"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf gotoWebWithUrl:@"https://www.maoxga.cn/xieyi.html" title:@"用户协议"];
    }];
    [titleText setTextHighlightRange:range3 color:[UIColor colorWithHexString:@"#46A0FF"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf gotoWebWithUrl:@"https://www.maoxga.cn/shequ.html" title:@"喵享家社区规则"];
    }];
    
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kScreenW, MAXFLOAT)];;
    YYTextLayout *titleTextLayout = [YYTextLayout layoutWithContainer:container text:titleText];
    self.choseLab.textLayout = titleTextLayout;
}

- (void)gotoWebWithUrl:(NSString *)url title:(NSString *)title {
    DCWebViewController *webVc = [[DCWebViewController alloc] initWithUrl:url];
    webVc.titleString = title;
    [self.navigationController pushViewController:webVc animated:YES];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}


#pragma mark  -----勾选协议------
- (void)choseclick:(UIButton*)btn{
    btn.selected = ! btn.selected;
}
#pragma mark -----手机号登录------
- (void)mobileLoginClick{
    if (!self.choseBtn.selected) {
        [self.view xjmakeToast:@"请勾选协议"];
        return;
    }
    MXMobileLoginVC *vc = [[MXMobileLoginVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)wxLoginClick {
    if (!self.choseBtn.selected) {
        [self.view xjmakeToast:@"请勾选协议"];
        return;
    }
    
        if([WXApi isWXAppInstalled]){//判断用户是否已安装微信App
    
            SendAuthReq *req = [[SendAuthReq alloc] init];
            req.state = @"APP";//用于保持请求和回调的状态，授权请求或原样带回
            req.scope = @"snsapi_userinfo";//授权作用域：获取用户个人信息
            [WXApi sendReq:req completion:^(BOOL success) {
                
            }];
    
        }else{
    
            //提示：未安装微信应用或版本过低
            [self.view xjmakeToast:@"请安装微信"];
        }
}

- (void)wxLoginSuccess:(NSNotification*)notification {
    NSDictionary *dict = notification.object;
//    NSLog(@"userInfo%@",dict);
    
    NSDictionary *param = @{@"registId":@"121c83f7612872ed1ec",
                            @"code":dict[@"code"]};
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:@"api/wxLogin" params:param httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            MXUserInfoModel *userInfo =  [MXUserInfoModel modelWithDictionary:dict[@"data"]];
            [DCObjectManager dc_saveUserData:userInfo.token forKey:DC_Token_Key];
            [DCCacheTool saveUserInfo:userInfo];
            UIWindow *window = [weakSelf getKeyWindow];
            window.rootViewController = [[DCNavigationController alloc] initWithRootViewController:[[DCTabbarController alloc] init]];
            [window makeKeyAndVisible];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (UIWindow *)getKeyWindow {
    
    UIWindow *keyWindow;
    if (@available(iOS 13.0, *)) {
        
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive) {
                
                keyWindow = windowScene.windows.firstObject;
                break;
            }
        }
    }
    return keyWindow;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
